package annotation;

import java.awt.event.ActionEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;


class DynamicAction extends AbstractAction {
	private static final long serialVersionUID = 7850192883519871860L;
	private Method method;
	private Class<?> clazz;
	
	DynamicAction(Menu menu, Class<?> clazz, Method method) throws InstantiationException, IllegalAccessException {
		super();
	
		this.clazz = clazz;
		this.method = method;
		//icon
		String icon = menu.icon();
		if (icon.trim().length()!=0) {
			File iconFile = new File(icon);
			if(iconFile.exists())
				putValue(SMALL_ICON, new ImageIcon(icon));
			else System.err.println("Icon:"+icon+" not found.");
		}

		// accelerator
		String accelerator = menu.raccourci();
		if(accelerator.trim().length() != 0) {
			putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(accelerator));
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			method.invoke(clazz, (Object[])null);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			e1.printStackTrace();
		}
	}
	
	void buildMenu(JMenu parent, String path) {
		int iSlash = path.indexOf('/');

		JMenuItem menu = null;
		if(iSlash == -1) {
			putValue(NAME, path);
			menu = new JMenuItem(this);
		} else {
			String name = path.substring(0, iSlash);
			for (int i = 0; i<parent.getItemCount(); i++) {
				JMenuItem mi = parent.getItem(i);
				if(mi != null && mi.getText().equals(name)) {
					menu = mi;
					break;
				}
			}
			if (menu==null)
				menu = new JMenu(name);
		}
		parent.add(menu);
		
		if (iSlash != -1) { 
			buildMenu((JMenu)menu, path.substring(iSlash+1));
		}
	}
}